#ifndef __MESSAGE_NODE_H__
#define __MESSAGE_NODE_H__


/*
    消息节点类，用于封装消息的头和体
    消息ID 数据长度  +  数据
*/

#include <boost/asio/detail/socket_ops.hpp>
#include <cstdint>
#include <cstring>
#include <boost/asio.hpp>

const uint16_t HEAD_MSG_ID = sizeof(uint16_t);
const uint16_t HEAD_MSG_LEN = sizeof(uint16_t);
const uint16_t HEAD_TOTAL_LEN = HEAD_MSG_ID + HEAD_MSG_LEN;

class MsgNode
{
public:
    using ptr = std::shared_ptr<MsgNode>;

    MsgNode(uint16_t len): _cur_len(0), _total_len(len)
    {
        _data = new char[len + 1];
        _data[len] = '\0';
    }

    ~MsgNode()
    {
        delete[] _data;
    }

    void Clear() 
    {
        _cur_len = 0;
        memset(_data, '\0', _total_len);
    }

public:
    uint16_t _cur_len;  // 当前处理长度
    uint16_t _total_len;// 总长度
    char* _data;        // 数据
};


class RecvNode: public MsgNode
{
public:
    using ptr = std::shared_ptr<RecvNode>;

    RecvNode(uint16_t len, uint16_t msg_id)
    :MsgNode(len)
    ,_msg_id(msg_id)
    {}

    uint16_t _msg_id;
};

class SendNode: public MsgNode
{
public:
    using ptr = std::shared_ptr<SendNode>;

    SendNode(const char* msg, uint16_t len, uint16_t msg_id)
    :MsgNode(len + HEAD_TOTAL_LEN)
    ,_msg_id(msg_id)
    {
        uint16_t net_id = boost::asio::detail::socket_ops::host_to_network_short(msg_id);
        uint16_t net_len = boost::asio::detail::socket_ops::host_to_network_short(len);

        memcpy(_data, &net_id, HEAD_MSG_ID);
        memcpy(_data + HEAD_MSG_ID, &net_len, HEAD_MSG_LEN);
        memcpy(_data + HEAD_TOTAL_LEN, msg, len);
    }

    uint16_t _msg_id;
};


#endif // __MESSAGE_NODE_H__